/* eslint-disable @typescript-eslint/no-explicit-any */
// @alias Trie
interface TrieNode extends Record<string, any> {
  next: TrieNode | null;
}
/**
 * 把字符串数组变成 TextMate 风格的正则字符串
 * @param {string[]} words
 * @returns {string}
 */
function buildRegexTrie(words: string[]): string {
  if (!words || words.length === 0) return "";

  // 1. 构建前缀树
  const trie: Record<string, any> = {};
  for (const w of words) {
    let node = trie;
    for (const ch of w) {
      node = node[ch] ??= {};
    }
  }

  // 2. 递归生成正则片段
  function build(node: Record<string, any>, prefix: string): string {
    // 当前节点无子节点
    const keys = Object.keys(node);
    if (keys.length === 0) {
      return prefix;
    }
    // 只有一个子节点，继续合并
    else if (keys.length === 1) {
      const [ch] = keys;
      return build(node[ch], prefix + ch);
    }
    // 多个子节点，分组

    const parts = keys.sort().map((ch) => build(node[ch], ch));
    console.log("trie", JSON.stringify(trie, null, 2));
    return `${prefix}(${parts.join("|")})`;
  }

  return build(trie, "");
}

// 示例
const words = ["a", "ab", "abc", "abcd", "abede"];
const regex = buildRegexTrie(words);
console.log(regex); // 输出示例: (ab|bc|e|f)
